package me.gavin

import android.os.Bundle
import androidx.lifecycle.observe
import coil.Coil
import coil.request.ImageRequest
import com.google.gson.JsonObject
import me.gavin.base.*
import me.gavin.databinding.TestBinding
import me.gavin.net.ClientAPI
import me.gavin.net.OKHttpCacheInterceptor
import me.gavin.util.fromJson
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine

class TestActivity : BindingVMActivity<TestBinding>() {

    override val viewModel by viewModel<TestViewModel>()

    override val layoutId = R.layout.test

    override fun afterCreate(savedInstanceState: Bundle?) {
        val adapter = BindingPagedAdapter<Img>(R.layout.test_item)
        binding.recycler.adapter = adapter
        viewModel.pagedList.observe(this) {
            adapter.submitList(it)
        }
    }
}

class TestViewModel(private val repo: TestRepo) : PageViewModel<Img>() {

    override suspend fun listData(page: Int): List<Img> {
        return repo.get(page)
    }
}

class TestRepo(private val api: ClientAPI) {

    suspend fun get(page: Int) = api
        .get(
            url = "https://gank.io/api/v2/data/category/Girl/type/Girl/page/$page/count/1",
            headers = mapOf(OKHttpCacheInterceptor.CACHE_CONTROL to OKHttpCacheInterceptor.MAX_STALE)
        )
        .fromJson<JsonObject>()!!
        .get("data").asJsonArray
        .map { it.asJsonObject["url"].asString }
        .map { getImage(it) }

    private suspend fun getImage(url: String): Img = suspendCoroutine { coro ->
        Coil.enqueue(ImageRequest
            .Builder(Gavin.app)
            .data(url)
            .target(
                onSuccess = {
                    coro.resume(Img(url, it.intrinsicWidth, it.intrinsicHeight))
                },
                onError = {
                    coro.resumeWithException(IllegalStateException())
                }
            )
            .build())
    }

}

data class Img(val url: String, var w: Int = 100, var h: Int = (80..150).random()) : Diffable {
    val ratioExt get() = "W,${h.toFloat() / w}"
}